package org.opu.pc.domain.dao.impl;

import java.sql.SQLException;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.SQLQuery;
import org.hibernate.Session;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.opu.pc.domain.dao.UserDao;
import org.opu.pc.domain.domains.security.User;
import org.opu.pc.util.Assert;
import org.springframework.orm.hibernate3.HibernateCallback;

public class UserDaoImpl extends AbstractHibernateDao<Integer, User> implements
		UserDao {
	
	@Override
	protected Class<User> getDomainClass() {
		return User.class;
	}

//	@Override
//	public User getGuestAccount() {
//		User user = get(GuestAccountId);
//		if (user == null){
////			user = new User(GuestAccountId, "Guest", "", "");
////			save(user);
//            user = hibernateTemplate.execute(new HibernateCallback<User>() {
//
//                @Override
//                public User doInHibernate(Session session) throws HibernateException, SQLException {
//                    SQLQuery query = session.createSQLQuery("insert into users "
//                            + "(id, name, password, email) values (?, ?, ?, ?)");
//                    query.setParameter(0, GuestAccountId);
//                    query.setParameter(1, GuestAccountName);
//                    query.setParameter(2, "");
//                    query.setParameter(3, "");
//                    Assert.True(query.executeUpdate() == 1);
//                    return null;
//                }
//            });
//            return getGuestAccount();
//		}
//		return user;
//	}

	@Override
	@SuppressWarnings("unchecked")
	public User getUserByName(String name) {
		DetachedCriteria criteria = DetachedCriteria.forClass(getDomainClass());
		criteria.add(Restrictions.eq("name", name));
		List<User> list = hibernateTemplate.findByCriteria(criteria);
		if (list.isEmpty()){
			return null;
		}
		return list.get(0);
	}

	@Override
	@SuppressWarnings("unchecked")
	public User getUserByNameAndPassword(String name, String pswd) {
		DetachedCriteria criteria = DetachedCriteria.forClass(getDomainClass());
		criteria.add(Restrictions.eq("name", name));
		criteria.add(Restrictions.eq("password", pswd));
		List<User> list = hibernateTemplate.findByCriteria(criteria);
		if (list.isEmpty()){
			return null;
		}
		return list.get(0);
	}
	
}
